﻿using System;
using System.Linq;
using System.Web.Mvc;
using Amba.ImageMultiPicker.Services;
using ImageResizer;
using Orchard.Core.Contents;
using Orchard.Themes;
using Orchard.UI.Admin;

namespace Amba.ImageMultiPicker.Controllers
{
    [HandleError]
    [Themed(false)]
    [Admin]
    public class ImageResizerController : Controller
    {
        private readonly IImageResizerService _imageResizerService;

        public ImageResizerController(IImageResizerService imageResizerService)
        {
            _imageResizerService = imageResizerService;
        }

        public ActionResult ResizedImage(
            string url, int width = 0, int height = 0, int maxWidth = 0, int maxheight = 0,
            CropMode cropMode = CropMode.Auto, ScaleMode scale = ScaleMode.Both,
            StretchMode stretchMode = StretchMode.Proportionally,
            string defaultImage = "/modules/amba.imagemultipicker/content/image_not_found.jpg")
        {
            if (string.IsNullOrWhiteSpace(url))
                return HttpNotFound();

            string ext = _imageResizerService.GetCleanFileExtension(url);
            if (!_imageResizerService.SupportedFileExtensions().Contains(ext))
            {
                throw new ArgumentException("Invalid file extension! suported file extensions are: " +
                                            string.Join(",", _imageResizerService.SupportedFileExtensions()));
            }
            var retValImageUrl = _imageResizerService.ResizeImage(url, width, height, maxWidth, maxheight, cropMode, scale, stretchMode);
            if (string.IsNullOrWhiteSpace(retValImageUrl))
            {
                retValImageUrl = _imageResizerService.ResizeImage(defaultImage, width, height, maxWidth, maxheight, cropMode, scale, stretchMode);  
            }
            if (string.IsNullOrWhiteSpace(retValImageUrl))
            {
                return HttpNotFound();
            }
            return Redirect(retValImageUrl);
        }
    }
}